package cn.hinglo.baseservice.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * @author HingLo
 * @createTime: 2018/1/4
 * @description: 日志记录
 */
@Component
@Aspect
@Slf4j
public class LogAspect {

    /***
     * 配置Aop切入的方法路径
     */
    @Pointcut("execution(public * cn.hinglo.*.controller..*(..))")
    public void log() {
    }

    /***
     * Aop拦截之前的操作
     *
     * @param proceedingJoinPoint 切点对象
     */
    @Before("log()")
    public void beforeLogger(JoinPoint proceedingJoinPoint) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert servletRequestAttributes != null;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        // 全路径
        String url = request.getRequestURL().toString();
        // 请求的方法类型
        String method = request.getMethod();
        // 请求的参数值
        String queryString = request.getQueryString();
        // 请求的具体的那个方法
        String classMethod = proceedingJoinPoint.getSignature().getDeclaringTypeName() + "." + proceedingJoinPoint.getSignature().getName();
        log.info("ServiceApi URL: {} ==> method: {} ==> classMethod:{} ==> params: {}", url, method, classMethod, queryString);
    }

    /**
     * 方法结束后执行的方法
     */
    @After("log()")
    public void afterLogger() {

    }

    /**
     * 用于拦截响应的值
     *
     * @param object 返回的结果对象
     */
    @AfterReturning(returning = "object", pointcut = "log()")
    public void doReturning(Object object) {
        log.info("Response:{}", object != null ? object.toString() : "服务器没有做出实体响应数据,可能图片");
        System.out
                .println("\n====================================================响应结束====================================================\n");

    }
}
